package com.nebula.util;

import com.nebula.common.TreeResult;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CcccX
 * @create 2019-01-11 15:52
 */
public class TreeNodeUtil {
    /**
     * <pre>
     * 构造树流程
     * 1.根节点--往下找到其子节点，构造第一层树
     * 2.根节点下的父节点--往下找到其子节点，构造第n层树
     * @param list 构造树所需要的数据  以ArrayList格式传入
     * @return 完整的树
     * </pre>
     */
    public static ArrayList<TreeResult> getTree(List<TreeResult> list) {
        ArrayList<TreeResult> treeResults = new ArrayList<>();
        for (TreeResult treeNode : list) {
            if ("0".equals(treeNode.getParentId())|| treeNode.getParentId().equals(treeNode.getId())) {
                treeNode.setChildren(getChildrenNode(treeNode.getId(), list));
                treeResults.add(treeNode);
            }
        }


        return treeResults;
    }

    /**
     * <pre>
     * 找到父节点的子节点
     * @param pid 父节点id
     * @param list 数据集合
     * @return 子节点
     * </pre>
     */
    private static ArrayList<TreeResult> getChildrenNode(String pid, List<TreeResult> list) {
        ArrayList<TreeResult> childrenNode = new ArrayList<>();
        for (TreeResult children : list) {
            if (pid.equals(children.getParentId())) {
                children.setChildren(getChildrenNode(children.getId(), list));
                childrenNode.add(children);
            }
        }
        return childrenNode;
    }
}
